<!-- 栏目管理 -->
<template>
    <el-button type="primary" @click="add('addP')" style="margin-bottom: 10px;" >新增根栏目</el-button>
    <!-- <el-button type="primary" plain @click="columnCopy()" :disabled="!userInfo.roleIdList.includes(1)" style="margin-bottom: 10px;">栏目复制</el-button> -->
    <el-table :data="data.tableData" row-key="id" table-layout="auto" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="栏目名称" width="200" />
        <el-table-column prop="description" label="描述" width="100" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="栏目状态" width="100">
            <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="success">已发布</el-tag>
                <el-tag v-if="scope.row.status === 0" type="danger">未发布</el-tag>
                <!-- <el-switch v-model="scope.row.status" inline-prompt @change="switchChange(scope.row)" :active-value="1" :inactive-value="0" active-text="启动" inactive-text="禁用" /> -->
            </template>
        </el-table-column>
        <el-table-column label="背景图" width="100">
            <template #default="scope">
                <img :src="scope.row.imageUrl" alt="" style="width: 100px; height: auto;">
            </template>
        </el-table-column>
        <el-table-column label="路径">
            <template #default="scope">
                {{getPath(scope.row)}}
            </template>
        </el-table-column>
        <!-- <el-table-column prop="approveState" label="审核状态" width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.approveState == 1" type="info">待提交</el-tag>
        <el-tag v-if="scope.row.approveState == 2" type="primary">待审核</el-tag>
        <el-tag v-if="scope.row.approveState == 3" type="warning">审核中</el-tag>
        <el-tag v-if="scope.row.approveState == 4" type="success">已通过</el-tag>
        <el-tag v-if="scope.row.approveState == 5" type="danger">已驳回</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="approveType" label="提交类型" width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.approveType == 1" type="primary">新增</el-tag>
        <el-tag v-if="scope.row.approveType == 2" type="warning">编辑</el-tag>
        <el-tag v-if="scope.row.approveType == 3" type="danger">删除</el-tag>
      </template>
    </el-table-column> -->
        <el-table-column prop="publishTime" label="发布时间" width="200" align="center" />
        <el-table-column prop="revokeTime" label="撤销时间" width="200" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="200" />
        <el-table-column prop="createdByName" label="创建人" width="100" />
        <el-table-column prop="updateTime" label="更新时间" width="200" />
        <el-table-column prop="modifiedByName" label="更新人" width="100" />
        <!-- <el-table-column prop="deleted" label="删除标识" width="80">
            <template #default="scope">
                <span v-if="scope.row.deleted === 0">正常</span>
                <span v-if="scope.row.deleted === 1">已删除</span>
            </template>
        </el-table-column> -->
        <el-table-column prop="" label="操作" width="600" fixed="right">
            <template #default="scope">
                <!-- parentId==0表示根栏目  
            userInfo.roleIdList.includes(1)当前用户角色中有管理员
            scope.row.agCategoryPermission.buttonPermissions当前栏目的按钮权限
            scope.row.approveState == 4表示审核通过
            scope.row.status发布状态
         -->
                <div style="display: flex; margin:0 15px">
                    <el-button type="primary" v-if="scope.row.parentId==0&&(userInfo.roleIdList.includes(1)||(scope.row.agCategoryPermission.buttonPermissions&&scope.row.agCategoryPermission.buttonPermissions.includes(7)))" @click="add('editP',scope.row)">编辑根栏目</el-button>
                    <el-button v-if="scope.row.parentId!=0&&(userInfo.roleIdList.includes(1)||(scope.row.agCategoryPermission.buttonPermissions&&scope.row.agCategoryPermission.buttonPermissions.includes(2)))" @click="add('editS',scope.row)">编辑子栏目</el-button>
                    <el-button v-if="userInfo.roleIdList.includes(1)||(scope.row.agCategoryPermission.buttonPermissions&&scope.row.agCategoryPermission.buttonPermissions.includes(1))" type="primary" @click="add('addS',scope.row)">
                        <el-icon>
                            <Plus />
                        </el-icon>添加子栏目
                    </el-button>
                    <el-button v-if="userInfo.roleIdList.includes(1)||(scope.row.agCategoryPermission.buttonPermissions&&scope.row.agCategoryPermission.buttonPermissions.includes(3))" type="danger" @click="deleteColumn(scope.row)">删除</el-button>
                    <el-upload v-if="scope.row.level==1" v-model:file-list="fileList" :action="action2" :headers="uploadHeaders" :show-file-list="false" style="margin-left:10px;" :on-success="(res) => handleSuccess(res, scope.row)">
                        <el-button type="primary">上传背景图</el-button>
                    </el-upload>
                    <!-- <div v-if="userInfo.roleIdList.includes(1)||(scope.row.agCategoryPermission.buttonPermissions&&scope.row.agCategoryPermission.buttonPermissions.includes(5))" style="display: inline-block; margin:0 15px">
                        <el-button v-if="scope.row.status === 0" type="success" plain @click="openTimeDialog(scope.row,1)">发布</el-button>
                        <el-button v-if="scope.row.status === 1" type="danger" plain @click="openTimeDialog(scope.row,0)">撤销</el-button>
                    </div> -->
                    <!-- <el-button v-if="['1','5'].includes(scope.row.approveState)" type="primary" @click="check(scope.row)">提交审核</el-button> -->
                    <!-- <el-upload v-if="scope.row.level==2" v-model:file-list="fileList" :action="action" :data="{categoryId:scope.row.id}" :show-file-list="false" style="margin-left:10px;">
                        <el-button type="primary">上传背景图</el-button>
                    </el-upload> -->
                    <!-- <el-button type="text" v-if="scope.row.parentId==0" @click="preview(scope.row)">预览</el-button> -->
                </div>

            </template>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getList" @current-change="getList" style="margin-top: 20px;display:flex;justify-content: flex-end;" />
    <dialogForm ref="dialogFormRef" @resetList="getList"></dialogForm>
    <ysColumnCopy ref="ysColumnCopyRef" @addOne="addOne" />

    <el-dialog v-model="timeDialog" :title="timeTitle" width="500">
        <el-radio-group v-model="timeType">
            <el-radio :value="0" border>立即{{timeTitle}}</el-radio>
            <el-radio :value="1" border>定时{{timeTitle}}</el-radio>
        </el-radio-group>
        <div style="margin-top: 10px;">
            <el-date-picker v-if="timeType==1&&timeTitle=='发布'" v-model="publishTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
            <el-date-picker v-if="timeType==1&&timeTitle=='撤销'" v-model="revokeTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="timeDialogOk">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
  <script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { listColumn, editPColumn, editSColumn, deletePColumn, deleteSColumn, submitReviewColumn } from '@/api/allApi'
import dialogForm from './dialogForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { useRouter } from 'vue-router'
import { getTime } from '@/utils/myMethod.js'
import cache from '@/utils/cache' //为了获取token

// let tableData = reactive([])
const action = ref(import.meta.env.VITE_API_URL + '/new/category/changeCategoryImage')
const action2 = ref(import.meta.env.VITE_API_URL + '/sys/file/upload?access_token=' + localStorage.getItem('maToken'))
const uploadHeaders = reactive({
	Accept: 'application/json, text/plain, */*',
	Authorization: cache.getToken()
}) //上传图片请求头
const fileList = ref([])

const userInfo = JSON.parse(localStorage.getItem('userInfo'))
const pageNum = ref(1) //第几页
const pageSize = ref(10) //每页多少条
const total = ref(0) //总条数
const data = reactive({
	tableData: []
})

onMounted(() => {
	getList()
})

const getList = () => {
	listColumn({
		websiteId: Number(localStorage.getItem('WebsiteId')), //网站id 1：鞍钢官网 2：博物馆
		pageNum: pageNum.value,
		pageSize: pageSize.value
	}).then((res: any) => {
		if (res.code === 0) {
			data.tableData = res.data.list
			total.value = res.data.total
		} else {
			ElMessage.success(res.msg)
		}
	})
}
// const switchChange = (row: any, type: number) => {
// 	let api = editPColumn
// 	let obj = {
// 		categoryId: row.id,
// 		status: type
// 	}
// 	if (row.parentId == 0) {
// 		api = editPColumn
// 	} else {
// 		api = editSColumn
// 		obj.parentId = row.parentId
// 	}
// 	api(obj).then(res => {
// 		if (res.code === 0) {
// 			ElMessage.success('操作成功')
// 			getList()
// 		} else {
// 		}
// 	})
// }
const dialogFormRef = ref()
const add = (type: string, row: any) => {
	dialogFormRef.value.init(type, row)
}
const deleteColumn = (row: any) => {
	let api = deletePColumn
	let type = ''
	if (row.parentId == 0) {
		api = deletePColumn
		type = '根'
	} else {
		api = deleteSColumn
		type = '子'
	}
	ElMessageBox.confirm(`是否删除${type}栏目？`, '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		api(row.id).then((res: any) => {
			if (res.code === 0) {
				ElMessage.success('已删除')
				getList()
			} else {
				ElMessage.error(res.msg)
			}
		})
	})
}
const router = useRouter()
const preview = (row: any) => {
	// 在新标签页中打开
	const routeData = router.resolve({
		path: `/preview`,
		query: {
			parentId: row.id,
			parentName: row.name,
			type: 'column'
		}
	})
	window.open(routeData.href, '_blank')
}

const check = (row: any) => {
	submitReviewColumn({
		businessType: '1',
		businessId: row.id
	}).then(res => {
		if (res.code === 0) {
			getList()
			ElMessage.success('提交成功')
		} else {
			ElMessage.error(res.msg)
		}
	})
}

import ysColumnCopy from '@/views/ys/ysColumnCopy.vue'
const ysColumnCopyRef = ref()
//表格勾选
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
	multipleSelection.value = val
	console.log(multipleSelection.value, 'multipleSelection.value')
}
//栏目复制
const columnCopy = () => {
	if (multipleSelection.value.length == 0) {
		return ElMessage.error('请选择要复制的栏目')
	}
	ysColumnCopyRef.value.init()
}
//添加一项
const addOne = (radio, suffix) => {
	const a = (children: any) => {
		for (let i of children) {
			if (radio == '1') {
				i.name = i.name + getTime(new Date(), 'YMD')
			} else if (radio == '2') {
				i.name = i.name + '01'
			} else if (radio == '3') {
				i.name = i.name + suffix
			}
			i.id = i.id + new Date().getTime()
			if (i.children) {
				a(i.children)
			}
		}
	}
	let arr = JSON.parse(
		JSON.stringify(
			multipleSelection.value.filter(item => {
				return item.level === 1
			})
		)
	)
	a(arr)
	for (let i of arr) {
		data.tableData.push(i)
	}
	console.log(data.tableData, '33')
}

const timeDialog = ref(false)
const timeTitle = ref('发布')
const timeType = ref(0)
const timeDialogRow = reactive({})
const publishTime = ref('')
const revokeTime = ref('')

const openTimeDialog = (row: any, type: number) => {
	timeDialog.value = true
	publishTime.value = row.publishTime
	revokeTime.value = row.revokeTime
	Object.assign(timeDialogRow, row)
	if (type == 1) {
		timeTitle.value = '发布'
	} else if (type == 0) {
		timeTitle.value = '撤销'
	}
}
const timeDialogOk = () => {
	let api = editPColumn
	let obj = {
		categoryId: timeDialogRow.id,
		publishTime: timeType.value == 1 ? publishTime.value : '',
		revokeTime: timeType.value == 1 ? revokeTime.value : ''
	}
	if (timeType.value == 0) {
		obj.status = timeTitle.value == '发布' ? 1 : 0
	}
	if (timeDialogRow.parentId == 0) {
		api = editPColumn
	} else {
		api = editSColumn
		obj.parentId = timeDialogRow.parentId
	}
	api(obj).then(res => {
		if (res.code === 0) {
			timeDialog.value = false
			ElMessage.success('操作成功')
			getList()
		} else {
		}
	})
}
//文件上传成功回调
const handleSuccess = (res: any, row: any) => {
	editPColumn({
		...row,
		categoryId: row.id,
		imageUrl: res.data.url
	}).then((res: any) => {
		if (res.code === 0) {
			ElMessage.success('操作成功')
			getList()
		} else {
		}
	})
}
const getPath = (row: any) => {
	let path = ''
	//目前只有两层，所以可以这样做
	if (row.level == 2) {
		let typePath = ''
		switch (row.templateType) {
			case 1: //通用模板（列表）
				typePath = '/subcomponent/CorporateCulturalLife'
				break
			case 2: //通用模板（全内容）
				typePath = '/subcomponent/GroupProfile'
				break
			case 3: //通用模板（图文）
				typePath = '/subcomponent/SolicitousCare'
				break
			case 4: //通用模板（图片）
				typePath = '/subcomponent/allImg'
				break
			case 5: //通用模板（视频）
				typePath = '/subcomponent/video'
				break
			case 6: //鞍钢楷模专属模版
				typePath = '/subcomponent/PatternOne'
				break
			case 7: //董事集团会专属模版
				typePath = '/subcomponent/GroupBoardfDirectors'
				break
			case 8: //主要荣誉专属模版
				typePath = '/subcomponent/PrestigiousAwards'
				break
			case 9: //集团高管专属模板
				typePath = '/subcomponent/GroupExecutives'
				break
			case 10: //鞍钢出版物专属模板
				typePath = '/subcomponent/VerticalSlideshow'
				break
			case 11: //时政要闻专属模板
				typePath = '/subcomponent/CurrentPoliticalAffairs'
				break
			case 12: //股票信息专属模板
				typePath = '/subcomponent/Stock'
				break
			case 13: //报告专属模板
				typePath = '/subcomponent/SustainabilityReport'
				break
			case 14: //产品专属模板
				typePath = '/subcomponent/Product'
				break
			case 15: //文化专属模板
				typePath = '/subcomponent/Culture'
				break
			default:
				break
		}
		let parentName = ''
		for (let item of data.tableData) {
			if (item.id == row.parentId) {
				parentName = item.name
				break
			}
		}
		path = typePath + '?name=' + parentName + '&idParent=' + row.parentId + '&idSon=' + row.id + '&nameSon=' + row.name
		return path
	}
}
</script>
  
  <style lang="scss" scoped>
//搭配el-table里的table-layout="auto"属性，再让每一列里的width为空即可展现出适应表格内容的列宽
:deep(.el-table .cell) {
	width: max-content;
	display: inline-block;
}
</style>
  